<template>
    <div>
        <ExcelExport
            :header="tHeader"
            :list="tableData"
            :filter-val="filterVal"
            btn-text="导出excel"
        />
        <UploadExcel
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
        />
        <el-table
            :data="tableData"
            stripe
            style="width: 100%"
        >
            <el-table-column
                prop="date"
                label="日期"
            />
            <el-table-column
                prop="name"
                label="姓名"
            />
            <el-table-column
                prop="address"
                label="地址"
            />
        </el-table>
    </div>
</template>

<script>
import { tableData } from './tableConfig';
import ExcelExport from '@/components/ExcelExport';
import UploadExcel from '@/components/UploadExcel';
import * as dayjs from 'dayjs';

const translateChinese = {
    日期: 'date',
    姓名: 'name',
    地址: 'address',
};

export default {
    components: {
        ExcelExport,
        UploadExcel,
    },
    props: {
        taskId: {
            type: Number,
            required: true,
        },
    },
    data() {
        return {
            tableData: Object.freeze(tableData),
            tHeader: ['日期', '姓名', '地址'],
            filterVal: ['date', 'name', 'address'],
        };
    },
    mounted() {
        console.log(this);
    },
    methods: {
        beforeUpload(file) {
            const isLt1M = file.size / 1024 / 1024 < 1;
            if (isLt1M) {
                return true;
            }
            this.$message({
                message: '最大只能上传 1MB 的文件',
                type: 'warning',
            });
            return false;
        },
        handleSuccess({ results, header }) {
            results = results.map((item) => {
                var userInfo = {};
                Object.keys(item).forEach((key) => {
                    if (translateChinese[key] === 'date') {
                        // 后端接口做了数据类型限制  要求转换时间类型
                        userInfo[translateChinese[key]] = this.formatDate(
                            item[key],
                        );
                    } else {
                        userInfo[translateChinese[key]] = item[key];
                        // 将原来中文对应的值赋值给原来英文对应的值
                    }
                });
                return userInfo;
            });
            this.tableData = results;
        },
        // 格式化excel中的日期
        formatDate(numb) {
            return dayjs(numb)
                .add(1, 'day')
                .subtract(1, 'millisecond')
                .format('YYYY-MM-DD HH:mm:ss');
        },
    },
};
</script>
